import { Global } from './../../common/global';
import { File } from '@ionic-native/file';
import { AppVersion } from '@ionic-native/app-version';
import { Network } from '@ionic-native/network';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { StatusBar } from '@ionic-native/status-bar';
import { Platform, AlertController, Loading, LoadingController, ToastController } from 'ionic-angular';
import { Toast } from '@ionic-native/toast';
import { FingerprintAIO } from '@ionic-native/fingerprint-aio';
import { FileOpener } from '@ionic-native/file-opener';
import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { Observable } from 'rxjs/Observable';
import { Diagnostic } from '@ionic-native/diagnostic';
import { InAppBrowser } from '@ionic-native/in-app-browser';
import { Vibration } from '@ionic-native/vibration';

/*
  Generated class for the NativeProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class NativeProvider {
  private loading: Loading;
  public  timer:number = 0;
  public  refreshTokenInterval;
  public  timerInterval;
  constructor(public http: HttpClient, private statusBar: StatusBar, private platform: Platform, private alertCtrl: AlertController, private loadingCtrl: LoadingController,
    private toastCtrl: ToastController, private toast: Toast, private network: Network,private diagnostic: Diagnostic,  private inAppBrowser: InAppBrowser,
    private finger: FingerprintAIO, private appversion: AppVersion, private file: File, private fileopener: FileOpener, private fileTransfer: FileTransfer,
    private vibration: Vibration) {
    console.log('Hello NativeProvider Provider');
  }

  isMobile(): boolean {
    return this.platform.is('mobile') && !this.platform.is('mobileweb');
  }

  setStatusStyle(){
    if(this.isMobile){
      this.statusBar.overlaysWebView(false);//web view 覆盖statusbar
      this.statusBar.styleLightContent(); //设置字体为浅色气体
      // this.statusBar.styleDefault(); // 使用黑色字体
      this.statusBar.backgroundColorByHexString('#488aff'); // 3261b3 设置背景颜色为蓝色
    }
  }

 /**
   * 只有一个确定按钮的弹出框.
   * 如果已经打开则不再打开
   */
  alert = (() => {
    let isExist = false;
    return (title: string, subTitle = '', message = '', callBackFun = null): void => {
      if (!isExist) {
        isExist = true;
        this.alertCtrl.create({
          title,
          subTitle,
          message,
          cssClass: 'alert-zIndex-highest',
          buttons: [{
            text: '确定', handler: () => {
              isExist = false;
              callBackFun && callBackFun();
            }
          }],
          enableBackdropDismiss: false
        }).present();
      }
    };
  })();

  /**
   * 统一调用此方法显示loading
   * @param content 显示的内容
   */
  showLoading(content = ''): void {
    if (this.loading) {// 如果loading已经存在则不再打开
      return;
    }
    const loading = this.loadingCtrl.create({
      content
    });
    loading.present();
    this.loading = loading;
  }

    /**
   * 关闭loading
   */
  hideLoading(): void {
    this.loading && this.loading.dismiss();
    this.loading = null;
  }

    /**
   * 统一调用此方法显示提示信息
   * @param message 信息内容
   * @param duration 显示时长
   */
  showToast(message = '操作完成', duration = 2000, position:string ="bottom" ): void {
    if (this.isMobile()) {
      this.toast.show(message, String(duration), position).subscribe();
    } else {
      this.toastCtrl.create({
        message,
        duration,
        position: position,
        showCloseButton: false
      }).present();
    }
  }
    /**
   * 获取网络类型 如`unknown`, `ethernet`, `wifi`, `2g`, `3g`, `4g`, `cellular`, `none`
   */
  getNetworkType(): string {
    if (!this.isMobile()) {
      return 'wifi';
    }
    return this.network.type;
  }

  /**
   * 判断是否有网络
   */
  isConnecting(): boolean {
    return this.getNetworkType() != 'none';
  }
  /**
   * 是否支持指纹识别
   */
  showFinger(){
    return new Promise((resolve,reject)=>{
      this.finger.isAvailable().then(
        data=>{
          this.finger.show({
            clientId: 'Fingerprint-Demo',
            clientSecret: 'password', //Only necessary for Android
            disableBackup:false,  //Only for Android(optional)
          }).then(
            data=>{
              resolve(true);
            },
            error=>{
              reject("指纹识别失败！");
            }
          );
        },
        error=>{
          reject("该设备不支持指纹识别或者没有开启指纹验证!");
        }
      );
    });
  }
  checkupdate(remoteversion) {
    this.getVersionNumber().then(
      localversion => {
        if (localversion != remoteversion) {
          this.showUpdate();
        }
      }
    );
  }
  getVersionNumber(): Promise<string> {
    return new Promise((resolve) => {
      this.appversion.getVersionNumber().then((value: string) => {
        resolve(value);
      }).catch(err => {
        console.log('getVersionNumber:' + err);
      });
    });
  }
  showUpdate() {
    //这里连接后台获取app最新版本号,然后与当前app版本号(this.getVersionNumber())对比
    //版本号不一样就需要申请,不需要升级就return
    this.alertCtrl.create({
      title: '升级',
      subTitle: '有新版本需要立马升级!',
      enableBackdropDismiss: false,
      buttons: [
        {
          text: '确定',
          handler: () => {
            // this.externalStoragePermissionsAuthorization().subscribe(data=>{
            //   this.downloadApp();
            // })
            this.openUrlByBrowser(Global.downLoadUrl);
          }
        }
      ]
    }).present();
  }
  /**
   * 下载安装app
   */
  downloadApp() {
      let backgroundProcess = false;
      let alert = this.alertCtrl.create({
        title: '下载进度：0%',
        enableBackdropDismiss: false,
        // buttons: [{
        //   text: '后台下载', handler: () => {
        //     backgroundProcess = true;
        //   }
        // }]
      });
      alert.present();

      const fileTransfer: FileTransferObject = this.fileTransfer.create();
      const apk = this.file.externalRootDirectory + 'hms_mobile.apk'; //apk保存的目录

      fileTransfer.download(Global.downLoadUrl, apk).then(() => {
        alert && alert.dismiss();
        this.fileopener.open(apk, 'application/vnd.android.package-archive').then().catch((e) => {
          console.log(e);
          this.alertCtrl.create({
            title: '前往网页下载',
            subTitle: '本地升级失败',
             enableBackdropDismiss: false,
            buttons: [{
              text: '确定', handler: () => {
                this.openUrlByBrowser(Global.downLoadUrl); // 打开网页下载
              }
            }
            ]
          }).present();
        });
      }).catch((e)=>{
        console.log(e);
        this.alert("升级失败");
      })

      let timer = null; // 由于onProgress事件调用非常频繁,所以使用setTimeout用于函数节流
        fileTransfer.onProgress((event: ProgressEvent) => {
          const progress = Math.floor(event.loaded / event.total * 100); // 下载进度
          if (!timer) {
            // 更新下载进度
            timer = setTimeout(() => {
              if (progress === 100) {
                alert && alert.dismiss();
              } else {
                if (!backgroundProcess) {
                  const title = document.getElementsByClassName('alert-title')[0];
                  title && (title.innerHTML = `下载进度：${progress}%`);
                }
              }
              clearTimeout(timer);
              timer = null;
            }, 1000);
          }
        });
  }

  openUrlByBrowser(url: string): void {
    this.inAppBrowser.create(url, '_system');
  }

    /**
   * 检测app是否有读取存储权限,如果没有权限则会请求权限
   */
  externalStoragePermissionsAuthorization = (() => {
    let havePermission = false;
    return () => {
      return Observable.create(observer => {
        if (havePermission) {
          observer.next(true);
        } else {
          const permissions = [this.diagnostic.permission.READ_EXTERNAL_STORAGE, this.diagnostic.permission.WRITE_EXTERNAL_STORAGE];
          this.diagnostic.getPermissionsAuthorizationStatus(permissions).then(res => {
            if (res.READ_EXTERNAL_STORAGE == 'GRANTED' && res.WRITE_EXTERNAL_STORAGE == 'GRANTED') {
              havePermission = true;
              observer.next(true);
            } else {
              havePermission = false;
              this.diagnostic.requestRuntimePermissions(permissions).then(res => {// 请求权限
                if (res.READ_EXTERNAL_STORAGE == 'GRANTED' && res.WRITE_EXTERNAL_STORAGE == 'GRANTED') {
                  havePermission = true;
                  observer.next(true);
                } else {
                  havePermission = false;
                  this.alertCtrl.create({
                    title: '缺少读取存储权限',
                    subTitle: '请在手机设置或app权限管理中开启',
                    buttons: [{text: '取消'},
                      {
                        text: '去开启',
                        handler: () => {
                          this.diagnostic.switchToSettings();
                        }
                      }
                    ]
                  }).present();
                  observer.error(false);
                }
              }).catch(err => {
                observer.error(false);
              });
            }
          }).catch(err => {
            observer.error(false);
          });
        }
      });
    };
  })();
  vibrate(){
    this.vibration.vibrate(500);
  }
}
